package Library;

import java.util.ArrayList;
import java.util.Collections;


public class ShelfDaoImpl implements ShelfDao {
	private ArrayList<Book> shelfList;// 书架

	public ShelfDaoImpl() {
		shelfList = new ArrayList<>();
	}

	public void addBook(Book e) {
		// 添加书籍
		if (e == null) {
			return;
		}
		// 书籍的编号是唯一的，每次都需创建新的书籍
		shelfList.add(e);

	}

	/**
	 * 根据id找下标
	 * 
	 * @param id
	 * @return 书籍的下标
	 */
	private int findById(Integer id) {
		for (int i = 0; i < shelfList.size(); i++) {
			if (shelfList.get(i).getId().equals(id))
				return i;
		}
		return -1;
	}
	/**
	 *  根据x找书,1是name，2是author
	 * @param x
	 * @param j
	 * @return
	 */
	public int findBook(Object x,int j) {
		int num=0;//个数
		switch (j) {
		case 1:
			for (int i = 0; i < shelfList.size(); i++) {
				if (shelfList.get(i).getName().equals(x)) {
					System.out.println(shelfList.get(i).toString());
					num++;
				}		
			}
			
			break;
		case 2:
			for (int i = 0; i < shelfList.size(); i++) {
				if (shelfList.get(i).getAuthor().equals(x)) {
					System.out.println(shelfList.get(i).toString());
					num++;
				}
					
			}
			break;
		default:
			break;
		}
		return num;
	}

	public boolean deleteBook(Book e) {
		// 删除书籍,下架
		if (e.getId() == null)
			return false;
		int index = findById(e.getId());
		if (index == -1) {// 未找到
			return false;
		} else {
			shelfList.remove(index);
		}

		return true;
	}

	public void showBook() {
		// 展示书架上的图书
		Collections.sort(shelfList);
		
		for (Book item : shelfList) {
			System.out.println(item);
		}
	}

	/**
	 * 根据id找书籍
	 * 
	 * @param id
	 * @return 书籍下标
	 */
	public Book getItemById(Integer id) {
		
		
		if (id == null)
			return null;
		int index = findById(id);
		if (index == -1) {// 未找到
			return null;
		} else {
			return shelfList.get(index);
		}
	}

}
